package com.qf.filter;

import com.qf.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**鉴权过滤器，判断消费者用户登录
 * 拦截所有请求，判断tomcat的session中是否有用户对象信息
 * 如果有放行，如果没有，说明用户未登录，重定向到登录页面
 * @author fy
 * @version V1.0
 * @Project day41
 * @Package com.qf.filter
 * @Description:
 * @Date 2022/5/23 10:08
 */
@WebFilter("/*")
public class PermFiler implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //1：获取用户的访问路径
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //获取到用户的访问路径
        String uriStr = request.getRequestURI();
        System.out.println("=====uriStr===="+uriStr);
        if (uriStr.lastIndexOf(".")>0){
            String extStr = uriStr.substring(uriStr.lastIndexOf("."));
            if (extStr != null){
                if (".js".equals(extStr)){
                    filterChain.doFilter(servletRequest, servletResponse);
                    return;
                }
            }
        }

        //2：判断用户路径，放行所有静态资源，放行用户登录，注册首页，商品查询等路径
        if(uriStr.contains("/login")||uriStr.contains("/code")
                ||uriStr.contains("/user")||uriStr.contains("/register")
                ||uriStr.contains(".css")||uriStr.contains("/admin")
                ||uriStr.contains("/index")
                ||uriStr.contains("/type")||uriStr.contains("/goods")
                ||uriStr.contains(".jpg")||uriStr.contains(".png")
                ||uriStr.contains(".gif") || uriStr.contains(".eot")
                ||uriStr.contains(".svg") || uriStr.contains(".ttf")
                ||uriStr.contains(".woff") || uriStr.contains(".woff2")){
            //放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //3：获取会话session对象
        HttpSession session = request.getSession();
        //4：判断会话中是否有消费者用户的对象信息
        User user = (User) session.getAttribute("loginUser");

        //5：有放行，到下一个过滤器
        if(user != null){
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //6：没有重定向到消费者登录面登录
            response.sendRedirect("/login.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
